<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Index extends Controller {

	public function action_index($tagid = 0)
	{
		try {
			$view = View::factory('index');
			$Marticle = Model::factory('Article');
			
			$pagination = Kohana::$config->load('pagination')->get('article');
			if (!empty($tagid)){
				$Mtag = Model::factory('Tag');
				$tag_re = $Mtag->get_name_by_tagid($tagid);
				$tag = !empty($tag_re[0]['name']) ? $tag_re[0]['name'] : '';
				$view->bind('tag', $tag);
				$view->bind('tagid', $tagid);
				
				$pagination['total_items'] = $Marticle->get_count_by_tagid($tagid, array('status' => 0));
				$pager = Pagination::factory($pagination);
				$articles['articles'] = $Marticle->get_by_tagid($tagid, $pager->offset, $pager->items_per_page, array('status' => 0));
			}else {
				$param = $this->request->param('stuff');
				if (!empty($param)){
					$param_arr = explode('/', $param);
				}
				$category = isset($param_arr[0]) ? $param_arr[0] : 0;
				
				$cond = array();
				$cond['status'] = 0;
				if ($category > 0){
					$cond['category'] = $category;
				}
				$pagination['total_items'] = $Marticle->get_count($cond);
				$pager = Pagination::factory($pagination);
				$articles['articles'] = $Marticle->get_list($pager->offset, $pager->items_per_page, $cond);
			}
			
			foreach ($articles['articles'] as &$article){
				if (preg_match("/<embed.*?>/iS", $article['content'], $matches)){
					$article['video'] = $matches[0];
				}else if (preg_match("/<img.*?>/iS", $article['content'], $matches)){
					$article['image'] = $matches[0];
				}
			}

			$articles['pager'] = $pager->render();
			$view->bind('articles', $articles);
			
			$page_title = Function_23dian::page_title() . ' - ershisandian.com';
			$view->bind('page_title', $page_title);
			
			// 页面右侧
			$right = Include_Right::right_content();
			$view->bind('right', $right);
			
		}catch (Exception $e){
			Kohana_Exception::log($e);
			$err_msg = Kohana_Exception::text($e);
			$view = View::factory('errors/error')
					->bind('err_msg', $err_msg);
		}
		
		$this->response->body($view);
	}
	
	public function action_tagid(){
		
		$param = $this->request->param('stuff');
		if (!empty($param)){
			$param_arr = explode('/', $param);
		}
		$tagid = isset($param_arr[0]) ? $param_arr[0] : 0;
		$this->action_index($tagid);
	}

}
